package cn.org.atool.generator.database.model;

import cn.org.atool.generator.util.GeneratorHelper;

/**
 * 数据库表到文件命名转换策略
 *
 * @author wudarui
 */
public enum Naming {
    /**
     * 不做任何改变，原样输出
     */
    no_change,
    /**
     * 下划线转驼峰命名
     */
    underline_to_camel;

    public static String underlineToCamel(String input) {
        if (input == null) {
            return null;
        }
        String name = input;
        if (!hasLowerChar(name)) {
            name = name.toLowerCase();
        }
        StringBuilder buff = new StringBuilder();
        boolean isUnderline = false;
        boolean first = true;
        for (char ch : name.toCharArray()) {
            if (ch < 128 && chars[ch] == 0) {
                if (!first) {
                    isUnderline = true;
                }
                continue;
            }
            buff.append(isUnderline ? String.valueOf(ch).toUpperCase() : ch);
            isUnderline = false;
            first = false;
        }
        return buff.toString();
    }

    /**
     * 有小写字母
     *
     * @param word word
     * @return true: 有小写字母
     */
    public static boolean hasLowerChar(String word) {
        for (char c : word.toCharArray()) {
            if (c >= 'a' && c <= 'z') {
                return true;
            }
        }
        return false;
    }

    private static final char[] chars = new char[128];

    static {
        for (int i = 0; i < 128; i++) {
            chars[i] = 0;
        }
        for (char c = 'A'; c <= 'Z'; c++) {
            chars[c] = 1;
        }
        for (char c = 'a'; c <= 'z'; c++) {
            chars[c] = 1;
        }
        for (char c = '0'; c <= '9'; c++) {
            chars[c] = 1;
        }
    }

    /**
     * 去掉指定的前缀
     *
     * @param name   字段名称
     * @param prefix 前缀
     * @return ignore
     */
    public static String removePrefix(String name, String... prefix) {
        if (GeneratorHelper.isBlank(name)) {
            return "";
        }
        if (prefix == null) {
            return name;
        }
        String lowerCase = name.toLowerCase();
        for (String pf : prefix) {
            if (lowerCase.startsWith(pf.toLowerCase())) {
                return name.substring(pf.length());
            }
        }
        return name;
    }

    /**
     * 实体首字母大写
     *
     * @param name 待转换的字符串
     * @return 转换后的字符串
     */
    public static String capitalFirst(String name) {
        if (!GeneratorHelper.isBlank(name)) {
            return name.substring(0, 1).toUpperCase() + name.substring(1);
        } else {
            return "";
        }
    }

    /**
     * 首字母小写
     *
     * @param name name
     * @return ignore
     */
    public static String lowerFirst(String name) {
        return name.substring(0, 1).toLowerCase() + name.substring(1);
    }
}